#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <arpa/inet.h>

int start_server() {
    int tcp_socket, tcp_accept, len_epoll, result, epfd, count_ready;
    struct sockaddr_in serverAddr, clientAddr;

    len_epoll = 20;

    tcp_socket = socket(AF_INET, SOCK_STREAM, 0);
    if(tcp_socket == -1) {
        perror("tcp socket 连接失败");
        return 1;
    }

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = ntohs(8082);
    serverAddr.sin_addr.s_addr = inet_addr("0.0.0.0");

    socklen_t len_serverAddr = sizeof(serverAddr);
    socklen_t len_clientAddr = sizeof(clientAddr);

    result = bind(tcp_socket, &serverAddr, len_serverAddr);
    if(result == -1) {
        perror("bind 失败");
        return 1;
    }

    epfd = epoll_create(len_epoll);
    if(epfd == -1) {
        perror("epoll_create 失败");
        return 1;
    }

    result = listen(int s, int backlog);
    if(result == -1) {
        perror("listen 失败");
        return 1;
    }

    int i;
    struct epoll_event epe, epes[len_epoll];
    epe.data.fd = tcp_socket;
    result = epoll_ctl(epfd, EPOLL_CTL_ADD, tcp_socket, epe);
    if(result == -1) {
        perror("epoll_ctl 添加失败");
        return 1; 
    }
    char buf[1024];
    char sendBuf[1024];
    ssize_t len_recv;

    while(1) {
        count_ready = epoll_wait(epfd, epes, len_epoll, -1);
        if(count_ready == -1) {
            perror("epoll_wait 失败");
            return 1;
        } else if(count_ready == 0) {
            continue;
        } else {
            for(i = 0; i < count_ready; i++) {
                if(epes[i].data.fd == tcp_socket) {
                    tcp_accept = accept(epes[i].data.fd, &clientAddr, &len_clientAddr);
                    if(result == -1) {
                        perror("epoll_wait 失败");
                        return 1;
                    }
                    epe.data.fd = tcp_accept;
                    result = epoll_ctl(epfd, EPOLL_CTL_ADD, tcp_accept, epe);
                    if(result == -1) {
                        perror("epoll_ctl add 失败");
                        return 1;
                    }
                } else {
                    bzero(buf, sizeof(buf));
                    len_recv = recvfrom(epes[i].data.fd, buf, sizeof(buf), 0, &clientAddr, &len_clientAddr);
                    if(len_recv == -1) {
                        perror("recvfrom 失败");
                        return 1;
                    }
                    //处理接收的消息
                    //发送消息

                    result = sendto(epes[i].data.fd, sendBuf, sizeof(sendBuf), 0, &clientAddr, sizeof(sendBuf));
                    if(result == -1) {
                        perror("sendto 失败");
                        return 1;
                    }
                }
            }
        }
    }
}

